var toolbar = [{
			text:'添加商品',
			iconCls:'icon-add',
			handler:addProduct
		},{
			text:'删除所选商品',
			iconCls:'icon-remove',
			handler:deleteProduct
		}];

if(action=='create'){
	toolbar[2] = {
			text:'加载订单采购',
			iconCls:'icon-reload',
			handler:loadOrderProducts
	}
}

//点击添加商品事件
function addProduct()
{
	$('#addProductsArea').dialog('open');
	doSearch();
}

//删除所选商品
function deleteProduct()
{
	var node = $('#products');
	var selections = node.datagrid('getSelections');
	for(var i in selections)
	{
		var rowIndex = node.datagrid('getRowIndex',selections[i]);
		node.datagrid('deleteRow',rowIndex);
	}
}

//搜索商品事件
function doSearch()
{
	var addProductsNode = $('#addProducts');
	addProductsNode.datagrid("loading");
	var inputValue = $('#searchProducts').val();
	var barcode = $('#searchBarcode').val();
	var supplierid = $('input[name="supplierid"]').val();
	if(!(supplierid>0)){
		alert('请选择供应商！');
		return false;
	}
	$.post('/admin/module.php?m=inventory&s=purchases.php&uri=recaches',{inputValue:inputValue,barcode:barcode,supplierid:supplierid},function(res){
		addProductsNode.datagrid({
			data:res
		});

	},'json');
}

//添加所选商品事件
function addSelectedProducts()
{
	var productsNode = $('#products');
	var selected = $('#addProducts').datagrid('getSelections');
	var productsData = productsNode.datagrid('getData');
	var total =  productsData.total + selected.length;
	var rows = productsData.rows;
	if(!(selected.length>0))
	{
		closeSearchProduct();
		return;
	}
	//检查是否已存在
	for(var i in selected)
	{
		for(var j in rows)
		{
			if(selected[i].id==rows[j].id)
			{
				alert('添加失败，此商品已存在于采购列表中	');
				return;
			}
		}
	}
	
	//合并
	var newRows = new Array();
	var index = 0;
	for(var i in selected)
	{
		var item = selected[i];
		newRows[index] = {"id":item.id,"pid":item.pid,"pic":item.pic,"pname":item.pname,"spec":item.spec,"pricebuy":item.cost_price,"currency_unit":item.currency_unit,"number":"0","unit":"个","shopid":item.shopid}
		index++;
	}
	for(var i in rows)
	{
		var item = rows[i];
		var key = selected.length + i;
		newRows[index] = item;
		index++;
	}
	var newData = {"total":total,"rows":newRows}
	productsNode.datagrid({
		data:newData
	});
	closeSearchProduct();
}

function closeSearchProduct()
{
	$('#addProducts').datagrid({
		data:{rows:[],total:0}
	});
	$('#addProductsArea').dialog('close');
}

//点击保存事件
function save()
{
	//获取输入的数据
	var title			= $('#title').val();
	var shopid 		= $('input[name="shopid"]').val();
	var supplierid = $('input[name="supplierid"]').val();
	var memo 		= $('input[name="memo"]').val();
	var purchase_price 		= $('input[name="purchase_price"]').val();
	var discount_price 		= $('input[name="discount_price"]').val();
	var express_price 		= $('input[name="express_price"]').val();
	var other_price 		= $('input[name="other_price"]').val();
	var products = $('#products').datagrid('getData');
	
	//检查参数
	if(!(products.total>0))
	{
		alert('采购商品不能为空');
		return;
	}
	if(title=='')
	{
		alert('采购名称不能为空');
		return;
	}
	if(shopid=='')
	{
		alert('仓库不能为空');
		return;
	}
	if(supplierid=='')
	{
		alert('供货商不能为空');
		return;
	}
	
	$('#products').datagrid('acceptChanges');
	
	//将products数据转为json
	var rows = products.rows;
	var jsonStr = "{";
	var currency_unit = "";
	for(var i in rows)
	{
		jsonStr += '"'+i+'":'+'{';
		for(var j in rows[i])
		{
			if(j=='pname' || j=='spec' || j=='pic')
			{
				continue;
			}
			if(j=='shopid'&&(rows[i][j]!=shopid)){
				if (!confirm('id 为'+rows[i]['pid']+'的商品已不在此仓库，请核查是否确认采购')){
				 return;
			   }
			}
			if(j=='currency_unit'){
				if(currency_unit==''){
					currency_unit = rows[i][j];
				}else{
					if(rows[i][j]!=currency_unit){
						alert('一个采购单不允许添加不同货币的商品');return;
					}
				}
			}
			jsonStr += '"'+j+'":"'+rows[i][j]+'",';
		}
		jsonStr = jsonStr.substring(0,jsonStr.length-1);
		jsonStr += '},'
	}
	jsonStr = jsonStr.substring(0,jsonStr.length-1);
	jsonStr += '}';
	
	$.post(window.location.href,{action:"create",paper_id:paper_id,title:title,shopid:shopid,supplierid:supplierid,memo:memo,purchase_price:purchase_price,discount_price:discount_price,express_price:express_price,other_price:other_price,currency_unit:currency_unit,products:jsonStr},function(res){
		if(res=='ok')
		{
			window.location.href = '/admin/module.php?m=inventory&s=purchases.php';
		}
		else
		{
			alert(res);
		}
	});
	
}

/**
 * 清空采购商品
 */
function deleteAllProducts(){
	var products = $('#products')
	products.datagrid('selectAll');
	deleteProduct()
}

/**
 * 选择负责人事件
 */
function selectedClass(t){
	var c=$('[name=classid]').val();
	var s= $('[name=shopid').val();
	var url = "/admin/module.php?m=inventory&s=purchases.php&uri=getSupplies&classid="+c+'&shopid='+s;
	var supplierid = $('#supplierid');
	supplierid.combobox('clear')
	supplierid.next().css('visibility','hidden')
	supplierid.combobox('reload',url)
//	deleteAllProducts();
}
function selectedSupplier(){
//	deleteAllProducts();
}
/**
 * 加载供应商
 * @param t
 */
function loadSuppliersSuccess(t){
	var supplierid = $('#supplierid')
	supplierid.next().css('visibility','visible')
}
/**
 * 加载订单采购商品
 */
function loadOrderProducts(){
	var supplierid = $('#supplierid')
	supplier = supplierid.combobox('getValue');
	if(supplier==""){
		$.messager.alert('提示','请先选择供货商');
		return;
	}
	var products = $('#products')
	var rowsObj = products.datagrid("getRows");
	if(rowsObj && rowsObj.length>0){
		$.messager.confirm('提示','加载订单采购商品将清空当前采购列表',function(r){
			if(r){
				deleteAllProducts();
				handlerOrderProducts(supplier)
			}
		});
	}else{
		handlerOrderProducts(supplier)		
	}
}
function handlerOrderProducts(supplierid){
	var productsNode = $('#products')
	productsNode.datagrid("loading")
	$.get('/admin/module.php?m=inventory&s=purchases.php&uri=getOrderProducts&supplierid='+supplierid,{},function(res){
		if(res && res.total>0){
			var rows = new Array();
			var index = 0;
			for(var i in res.rows)
			{
				var item = res.rows[i];
				rows[index] = {"id":item.id,"pid":item.pid,"pic":item.pic,"pname":item.pname,"spec":item.spec,"pricebuy":item.cost_price,"number":item.number,"unit":"个"}
				index++;
			}
			var newData = {"total":res.total,"rows":rows}
			productsNode.datagrid({
				data:newData
			});
		}
		productsNode.datagrid("loaded")
	},'json');
}


$(function(){
	//默认加载已有商品
	if(productsData!=null)
	{
		$('#products').datagrid({data:productsData});
	}
	if (action == 'create') {
		selectedClass();
	}
	//点击编辑事件
	var lastIndex;
	$('#products').datagrid({
		onClickRow:function(rowIndex){
			if (lastIndex != rowIndex){
				$(this).datagrid('endEdit', lastIndex);
				$(this).datagrid('beginEdit', rowIndex);
			}
			lastIndex = rowIndex;
		},
		onBeginEdit:function(rowIndex){
//			var editors = $('#products').datagrid('getEditors', rowIndex);
//			var n1 = $(editors[0].target);
//			var n2 = $(editors[1].target);
//			var n3 = $(editors[2].target);
//			n1.add(n2).numberbox({
//				onChange:function(){
//					var cost = n1.numberbox('getValue')*n2.numberbox('getValue');
//					n3.numberbox('setValue',cost);
//				}
//			})
		},
	});
});


